package com.taoyibao.hongcanting.ui.restaurant.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;

import com.taoyibao.hongcanting.R;
import com.taoyibao.hongcanting.base.fragment.BaseFragmentPresenter;
import com.taoyibao.hongcanting.cache.SpUtils;
import com.taoyibao.hongcanting.constant.CodeConstant;
import com.taoyibao.hongcanting.constant.NetCode;
import com.taoyibao.hongcanting.dialog.DialogComment;
import com.taoyibao.hongcanting.event.EventGift;
import com.taoyibao.hongcanting.http.DefaultTransformer;
import com.taoyibao.hongcanting.http.JsonApiWrapper;
import com.taoyibao.hongcanting.http.ProgressSubscriber;
import com.taoyibao.hongcanting.model.BalanceModel;
import com.taoyibao.hongcanting.model.CompanyBaseModel;
import com.taoyibao.hongcanting.model.GiftInfoModel;
import com.taoyibao.hongcanting.model.GiftMode;
import com.taoyibao.hongcanting.model.UserTableModel;
import com.taoyibao.hongcanting.ui.mine.activity.RechargeActivity;
import com.taoyibao.hongcanting.ui.restaurant.area.GiftSendArea;
import com.taoyibao.hongcanting.ui.restaurant.delegate.GiftFragmentDelegate;
import com.taoyibao.hongcanting.utils.CodeUtils;
import com.taoyibao.hongcanting.utils.DataUtils;
import com.taoyibao.hongcanting.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author TangAnna
 * @description: 礼物模块
 * @date :${DATA} 11:53
 */
public class GiftFragment extends BaseFragmentPresenter<GiftFragmentDelegate> implements GiftSendArea.GiftSendListener, DialogComment.DialogCommentInterfaca {
    private List<Fragment> mFragments;
    private GiftMode mGiftMode;
    private GiftSendArea mGiftSendArea;
    /**
     * 被选中的礼物
     */
    private GiftInfoModel mChooseGift;
    /**
     * 用户的余额
     */
    private double mBalance;
    private String mTableId = null;//桌位Id

    @Override
    protected Class<GiftFragmentDelegate> getDelegateClass() {
        return GiftFragmentDelegate.class;
    }

    /**
     * @param giftMode
     * @return
     */
    public static GiftFragment getInstance(GiftMode giftMode) {
        GiftFragment fragment = new GiftFragment();
        Bundle bundle = new Bundle();
        bundle.putParcelable(CodeConstant.GIFT_KEY, giftMode);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onResume() {
        super.onResume();
        getBalance();
        getTableStatus();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (viewDelegate != null && isVisibleToUser) {
            getBalance();
            getTableStatus();
        }
    }

    @Override
    protected void bindEvenListener() {
        super.bindEvenListener();
        EventBus.getDefault().register(this);
        mGiftSendArea = viewDelegate.get(R.id.layout_send);
        mGiftSendArea.setGiftSendListener(this);
        mFragments = new ArrayList<>();
        mGiftMode = getArguments().getParcelable(CodeConstant.GIFT_KEY);
        List<GiftInfoModel> info = mGiftMode.info;
        //分数据 每8个数据一组 是一页的数据
        List<List<?>> lists = DataUtils.splitList(info, 8);
        for (int i = 0; i < lists.size(); i++) {
            ArrayList<GiftInfoModel> arr = new ArrayList<>();
            List<GiftInfoModel> data = (List<GiftInfoModel>) lists.get(i);
            arr.addAll(data);
            mFragments.add(GiftPageFragmnet.getInstance(arr));
        }
        viewDelegate.setData(getChildFragmentManager(), mFragments);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 获取用户余额
     */
    public void getBalance() {
        JsonApiWrapper.getApiService().userBalance(SpUtils.getToken(), SpUtils.getMemberId())
                .compose(new DefaultTransformer<CompanyBaseModel<List<BalanceModel>>>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel<List<BalanceModel>>>(getContext(), false) {
                    @Override
                    public void onNext(CompanyBaseModel<List<BalanceModel>> result) {
                        if (result.code == NetCode.HTTP_200 && result.data != null && result.data.size() > 0) {
                            BalanceModel balanceModel = result.data.get(0);
                            mBalance = balanceModel.balance + balanceModel.interests;
                            //设置显示余额
                            mGiftSendArea.setData(CodeUtils.formatAmountUnit(mBalance));
                        } else {
                            super.onNext(result);
                        }
                    }
                });
    }

    /**
     * 获取当前用户的就餐状态
     */
    public void getTableStatus() {
        JsonApiWrapper.getApiService().tableStatus(SpUtils.getToken())
                .compose(new DefaultTransformer<CompanyBaseModel<List<UserTableModel>>>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel<List<UserTableModel>>>(getContext(), false) {
                    @Override
                    public void onNext(CompanyBaseModel<List<UserTableModel>> result) {
                        if (result.code == NetCode.HTTP_200 && result.data != null && result.data.size() > 0) {
                            UserTableModel userTableModel = result.data.get(0);
                            if (userTableModel != null && !TextUtils.isEmpty(userTableModel.desk_code)) {
                                mTableId = userTableModel.desk_code;
                            }
                        }else {
                            super.onNext(result);
                        }
                    }
                });
    }

    /**
     * 发送事件
     */
    @Override
    public void onSend() {
        if (mChooseGift == null) {
            ToastUtils.showToast(CodeUtils.getIdString(R.string.map_chooseGift));
            return;
        }
        //账户余额充足
        if (mBalance >= mChooseGift.price) {
            sendGift(mChooseGift);
        } else {//余额不足
            DialogComment dialogComment = new DialogComment(CodeUtils.getIdString(R.string.dialog_recharge), this);
            dialogComment.showDilaog(getChildFragmentManager(), "ScreenFragment");
        }
    }

    /**
     * 送礼物的页面点击时收到的消息 发送时使用数据
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void EveentMessage(EventGift eventGift) {
        //获取到当前页面选择的数据了
        mChooseGift = eventGift.mGiftInfoModel;
    }

    /**
     * 调用接口发送礼物
     */
    public void sendGift(GiftInfoModel giftInfoModel) {
        JsonApiWrapper.getApiService().sendGift(SpUtils.getToken(), giftInfoModel.id, giftInfoModel.price + "", null, mTableId)
                .compose(new DefaultTransformer<CompanyBaseModel>())
                .subscribe(new ProgressSubscriber<CompanyBaseModel>(getContext(), true) {
                    @Override
                    public void onNext(CompanyBaseModel result) {
                        if (result.code == NetCode.HTTP_200) {
                            ToastUtils.showToast(CodeUtils.getIdString(R.string.map_zengSongSuccess));
                            getBalance();
                        } else {
                            super.onNext(result);
                        }
                    }
                });
    }

    @Override
    public void onConfirmListener() {
        startActivity(new Intent(getContext(), RechargeActivity.class));
    }
}
